package com.application.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.application.domain.User;
import com.application.service.Impl.UserServiceImpl;
import com.application.service.UserService;
import com.application.util.HttpUtil;
import com.application.util.WechatUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;

@Api(tags = "微信授权登录")
@RequestMapping
@RestController
public class WXLogin {

    @Resource
    UserService userService;

    @Resource
    private HttpUtil httpUtil;
    @PutMapping("wx/login")
    public Result user_login(@RequestParam(value = "code",required = false) String code){

        //接收小程序传输过来的code
        //然后进行验证
        System.out.println(code);
        String openid = httpUtil.getOpenid(code);

        //几首微信接口服务  获取返回参数
//        System.out.println(code);

//        System.out.println(sessionKeyOrOpenId==null);

        if(openid==null){
            System.out.println("无法正确获取信息");
            return new Result(Code.LOGIN_ERR,null,"无法正确获取信息");
        }
            //根据返回的user实体类  判断用户是否为新用户   是新用户   就保存到数据库中
            LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
            lqw.eq(User::getOpenid, openid);
            User user = userService.getOne(lqw);
            int save=0;
            // 是 新用户   就直接新添加都数据库中
            if (user == null) {
                User user1= new User();
                user1.setOpenid(openid);
                save = userService.save(user1);
            }


        return new Result(Code.LOGIN_OK,openid,"登录成功");
    }
}
